package com.lagou.miaosha.rocketmq.controller;

import com.alibaba.fastjson.JSONObject;
import com.lagou.miaosha.rocketmq.mapper.OrderMapper;
import com.lagou.miaosha.rocketmq.pojo.Order;
import com.lagou.miaosha.rocketmq.pojo.Stock;
import com.lagou.miaosha.rocketmq.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.Lock;

/**
 * @Description TODO
 * @Classname OrderController
 * @Date 2021/8/1 17:06
 * @Author ch'ien
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private IStockService stockService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @Value("${TOPIC.MS}")
    private String topic;


    @GetMapping("/create")
    public String createOrderWithMq(@RequestParam(value = "gid") Integer gid,
                                    @RequestParam(value = "userId") Integer userId) {
        try {
            // 检查缓存中商品是否还有库存
            Integer count = stockService.getStockCount(gid);
            if (count == 0) {
                return "秒杀请求失败，库存不足.....";
            }
            stockService.decrement (gid);
            // 有库存，则将用户id和商品id封装为消息体传给消息队列处理
            // 注意这里的有库存和已经下单都是缓存中的结论，存在不可靠性，在消息队列中会查表再次验证
            log.info("有库存：[{}]", count);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("gid", gid);
            jsonObject.put("userId", userId);
            rocketMQTemplate.convertAndSend(topic, jsonObject.toJSONString());

            return "秒杀请求提交成功";
        } catch (Exception e) {
            log.error("下单接口：异步处理订单异常：", e);
            return "秒杀请求失败，服务器正忙.....";
        }

    }


    @GetMapping("/pay/{id}")
    public String pay(@PathVariable String id) {

        Order one = orderMapper.getOneByOrderNo(id);
        if (one == null || Objects.equals(one.getStatus(), 2)){
            List<Order> list = orderMapper.getListForCancel();
            return "订单不存在或失效";
        }
        one.setStatus(1);
        orderMapper.update(one);
        return "sucessful";
    }


    @GetMapping("/list")
    public List<Order> list() {

        List<Order> list = orderMapper.getListForCancel();
        return list;

    }

    @GetMapping("/stock/list")
    public List<Stock> listStock() {

        List<Stock> list = stockService.getList();
        return list;

    }
}
